﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using BPMS.Utility.Web;

namespace BPMS.Web.Extends.Attributes
{
    /// <summary>
    /// 登录验证
    /// </summary>
    public enum CheckLoginEnum
    {
        /// <summary>
        /// 需要登录才能访问
        /// </summary>
        Login,
        /// <summary>
        /// 不需登录就可访问
        /// </summary>
        Public
    }

    /// <summary>
    /// 用户验证过滤器
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class AdminAuthorizationAttribute : AuthorizeAttribute, IAuthorizationFilter
    {
        /// <summary>
        /// 登陆验证
        /// </summary>
        public CheckLoginEnum CheckLogin { get; set; }
        public AdminAuthorizationAttribute()
        {
            this.CheckLogin = CheckLoginEnum.Login;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
            {
                throw new InvalidOperationException("子操作缓存否处于活动状态时不允许使用此操作");
            }
            if (filterContext.HttpContext.Session.IsNewSession)
            {
                if (CheckLogin == CheckLoginEnum.Login)
                {
                    if (filterContext.HttpContext.Request.IsAuthenticated)//已通过身份验证
                    {
                        //TODO 验证是否有权限访问该页面
                    }
                    else
                    {
                        this.HandleUnauthorizedRequest(filterContext);
                    }
                }
            }
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                {
                    Data = new { IsSuccess = false, Message = "登陆超时,请重新登陆!" },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }
            else
            {
                filterContext.Result = new RedirectResult(URLUtility.RootUrl + "account/login");
            }
        }
    }
}
